(function(exports,main_core,main_core_events){"use strict";function _classStaticPrivateFieldSpecSet(e,t,i,s){_classCheckPrivateStaticAccess(e,t);_classCheckPrivateStaticFieldDescriptor(i,"set");_classApplyDescriptorSet(e,i,s);return s}function _classApplyDescriptorSet(e,t,i){if(t.set){t.set.call(e,i)}else{if(!t.writable){throw new TypeError("attempted to set read only private field")}t.value=i}}function _classStaticPrivateFieldSpecGet(e,t,i){_classCheckPrivateStaticAccess(e,t);_classCheckPrivateStaticFieldDescriptor(i,"get");return _classApplyDescriptorGet(e,i)}function _classCheckPrivateStaticFieldDescriptor(e,t){if(e===undefined){throw new TypeError("attempted to "+t+" private static field before its declaration")}}function _classCheckPrivateStaticAccess(e,t){if(e!==t){throw new TypeError("Private static access of wrong provenance")}}function _classApplyDescriptorGet(e,t){if(t.get){return t.get.call(e)}return t.value}var Options=function(){function e(){babelHelpers.classCallCheck(this,e)}babelHelpers.createClass(e,null,[{key:"getEventName",value:function e(t){return[this.getEventNamespace()].concat(babelHelpers.toConsumableArray(t)).join(":")}},{key:"getEventNamespace",value:function e(){return"BX:Main:Uploader:"}},{key:"calibratePostSize",value:function e(t,i){if(t<=0){return}if(t<this.defaultSettings["estimatedTimeForUploadFile"]){var s=[this.defaultSettings["currentPostSize"]*2,this.defaultSettings["phpPostMaxSize"]];if(i>0){s.push(Math.ceil(i*this.defaultSettings["estimatedTimeForUploadFile"]*1e3/t))}this.defaultSettings["currentPostSize"]=Math.min.apply(Math,s)}else{this.defaultSettings["currentPostSize"]=Math.max(Math.ceil(this.defaultSettings["currentPostSize"]/2),this.defaultSettings["phpPostMinSize"])}this.defaultSettings["currentPostSize"]=Math.max(this.defaultSettings["currentPostSize"],this.defaultSettings["phpPostMinSize"])}},{key:"getUploadLimits",value:function e(t){if(!this.defaultSettings){this.defaultSettings={currentPostSize:5.5*1024*1024,phpPostMinSize:5.5*1024*1024,phpUploadMaxFilesize:Math.min(/^d+$/.test(main_core.Loc.getMessage("phpUploadMaxFilesize"))?main_core.Loc.getMessage("phpUploadMaxFilesize"):5*1024*1024,5*1024*1024),phpMaxFileUploads:Math.max(/^d+$/.test(main_core.Loc.getMessage("phpMaxFileUploads"))?main_core.Loc.getMessage("phpMaxFileUploads"):20,20),phpPostMaxSize:/^d+$/.test(main_core.Loc.getMessage("phpPostMaxSize"))?main_core.Loc.getMessage("phpPostMaxSize"):11*1024*1024,estimatedTimeForUploadFile:10*60,maxSize:this.getMaxSize()}}if(t){return this.defaultSettings[t]}return this.defaultSettings}},{key:"getFileTypes",value:function e(){return["A","I","F"]}},{key:"getImageExtensions",value:function e(){return["jpg","bmp","jpeg","jpe","gif","png","webp"]}},{key:"getMaxSize",value:function t(){if(_classStaticPrivateFieldSpecGet(this,e,_quota)!==null&&!_classStaticPrivateFieldSpecGet(this,e,_quota)){if(/^\d+$/.test(main_core.Loc.getMessage("bxQuota"))){_classStaticPrivateFieldSpecSet(this,e,_quota,parseInt(main_core.Loc.getMessage("bxQuota")))}else{_classStaticPrivateFieldSpecSet(this,e,_quota,null)}}return _classStaticPrivateFieldSpecGet(this,e,_quota)}},{key:"decrementMaxSize",value:function t(i){if(this.getMaxSize()!==null){_classStaticPrivateFieldSpecSet(this,e,_quota,_classStaticPrivateFieldSpecGet(this,e,_quota)-i)}return _classStaticPrivateFieldSpecGet(this,e,_quota)}},{key:"getMaxTimeToUploading",value:function e(){return 900}},{key:"getVersion",value:function e(){return"1"}}]);return e}();babelHelpers.defineProperty(Options,"defaultSettings",null);var _quota={writable:true,value:void 0};babelHelpers.defineProperty(Options,"uploadStatus",{ready:"upload is ready",preparing:"upload is not started, but preparing",inProgress:"upload is in active streaming",done:"upload is in successfully done",error:"upload is in finished with errors",stopped:"PAUSE"});babelHelpers.defineProperty(Options,"fileStatus",{ready:"fileIsReady",removed:"fileIsRemoved",restored:"fileIsRestored",errored:"fileIsBad"});var DropZone=function(){function e(t){babelHelpers.classCallCheck(this,e);if(main_core.Type.isStringFilled(t)){t=document.getElementById(t)}if(main_core.Type.isDomNode(t)&&BX.DD&&BX.ajax.FormData.isSupported()){this.initialize(t)}}babelHelpers.createClass(e,[{key:"initialize",value:function e(t){var i=this;this.dndObject=new BX.DD.dropFiles(t);if(!this.dndObject||!this.dndObject.supported()){return}var s={dropFiles:function e(t){var s=babelHelpers.slicedToArray(t.compatData,2),a=s[0],r=s[1];if(r&&r["dataTransfer"]&&r["dataTransfer"]["items"]&&r["dataTransfer"]["items"].length>0){var n=false;var o=[];var l;for(var d=0;d<r["dataTransfer"]["items"].length;d++){l=r["dataTransfer"]["items"][d];if(l["webkitGetAsEntry"]&&l["getAsFile"]){n=true;var u=l["webkitGetAsEntry"]();if(u&&u.isFile){o.push(l["getAsFile"]())}}}if(n)a=o}main_core_events.EventEmitter.emit(i,Options.getEventName("caught"),{files:a})},dragEnter:function e(t){var s=babelHelpers.slicedToArray(t.compatData,1),a=s[0];var r=false;if(a&&a["dataTransfer"]&&a["dataTransfer"]["types"]){for(var n=0;n<a["dataTransfer"]["types"].length;n++){if(a["dataTransfer"]["types"][n]==="Files"){r=true;break}}}if(r){i.dndObject.DIV.classList.add("bxu-file-input-over");BX.onCustomEvent(i,"dragEnter",[a])}},dragLeave:function e(t){var s=babelHelpers.slicedToArray(t.compatData,1),a=s[0];i.dndObject.DIV.classList.remove("bxu-file-input-over");BX.onCustomEvent(i,"dragLeave",[a])}};main_core_events.EventEmitter.subscribe(this.dndObject,"dropFiles",s.dropFiles);main_core_events.EventEmitter.subscribe(this.dndObject,"dragEnter",s.dragEnter);main_core_events.EventEmitter.subscribe(this.dndObject,"dragLeave",s.dragLeave)}},{key:"destroy",value:function e(){main_core_events.EventEmitter.unsubscribeAll(this.dndObject);delete this.dndObject.DIV;delete this.dndObject}}]);return e}();var buildAjaxPromiseToRestoreCsrf=function e(t,i){i=i||false;var s=Object.assign({},t);var a=null;t.onrequeststart=function(e){a=e};var r=BX.ajax.promise(t);return r.then((function(t){if(!i&&main_core.Type.isPlainObject(t)&&t["errors"]){var a=false;t.errors.forEach((function(e){if(e.code==="invalid_csrf"&&e.customData.csrf){BX.message({bitrix_sessid:e.customData.csrf});s.headers=s.headers||[];s.headers=s.headers.filter((function(e){return e&&e.name!=="X-Bitrix-Csrf-Token"}));s.headers.push({name:"X-Bitrix-Csrf-Token",value:BX.bitrix_sessid()});a=true}}));if(a){return e(s,true)}}return t})).then((function(e){var t=new BX.Promise;t.fulfill(e);return t})).catch((function(t){var i=t.reason,r=t.data;if(i==="status"&&r&&(String(r).indexOf("503")>=0||String(r).indexOf("504")>=0)){s["50xCounter"]=(s["50xCounter"]||0)+1;if(s["50xCounter"]<=2){var n=a.getAllResponseHeaders().trim().split(/[\r\n]+/);var o={};n.forEach((function(e){var t=e.split(": ");var i=t.shift().toLowerCase();o[i]=t.join(": ")}));var l=null;if(o["retry-after"]&&/\d+/.test(o["retry-after"])){l=parseInt(o["retry-after"])}var d=new BX.Promise;setTimeout((function(){d.fulfill()}),(l||20)*1e3);return d.then((function(){return e(s)}))}}var u=new BX.Promise;if(main_core.Type.isPlainObject(r)&&r.status&&r.hasOwnProperty("data")){u.reject(r)}else{u.reject({status:"error",data:{ajaxRejectData:r},errors:[{code:"NETWORK_ERROR",message:"Network error"}]})}return u}))};var Stream=function(e){babelHelpers.inherits(t,e);function t(){var e;babelHelpers.classCallCheck(this,t);e=babelHelpers.possibleConstructorReturn(this,babelHelpers.getPrototypeOf(t).call(this));e.setEventNamespace(Options.getEventNamespace());e.onprogress=e.onprogress.bind(babelHelpers.assertThisInitialized(e));e.onprogressupload=e.onprogressupload.bind(babelHelpers.assertThisInitialized(e));return e}babelHelpers.createClass(t,[{key:"send",value:function e(t,i){var s=this;this.deltaTime=-1*(new Date).getTime();this.totalSize=null;buildAjaxPromiseToRestoreCsrf({method:"POST",dataType:"json",url:t,data:i,timeout:Options.getMaxTimeToUploading(),preparePost:false,headers:[{name:"X-Bitrix-Csrf-Token",value:BX.bitrix_sessid()},{name:"X-Bitrix-Site-Id",value:BX.message.SITE_ID||""}],onprogress:this.onprogress,onprogressupload:this.onprogressupload}).then((function(e){s.done({status:"success",data:e})})).catch((function(e){var t=e.errors,i=e.data;s.done({status:"failed",errors:t.map((function(e){var t=e.code,i=e.message;return i})),data:i})})).catch((function(e){s.done({status:"failed",errors:["Unexpected server response."],data:e})}))}},{key:"onprogress",value:function e(t){}},{key:"onprogressupload",value:function e(t){var i=5;if(babelHelpers.typeof(t)=="object"&&t.lengthComputable){i=t.loaded*100/(t["total"]||t["totalSize"]);this.totalSize=t["total"]||t["totalSize"]}else if(t>i)i=t;i=i>5?i:5;this.emit("progress",i)}},{key:"done",value:function e(t){this.deltaTime+=(new Date).getTime();Options.calibratePostSize(this.deltaTime,this.totalSize);this.emit("done",t)}},{key:"destroy",value:function e(){console.log("Clear all from stream")}}]);return t}(main_core_events.EventEmitter);function _classPrivateFieldInitSpec(e,t,i){_checkPrivateRedeclaration(e,t);t.set(e,i)}function _checkPrivateRedeclaration(e,t){if(t.has(e)){throw new TypeError("Cannot initialize the same private elements twice on an object")}}var _currentFileToUpload=new WeakMap;var PackageFile=function(e){babelHelpers.inherits(t,e);function t(e,i){var s;babelHelpers.classCallCheck(this,t);s=babelHelpers.possibleConstructorReturn(this,babelHelpers.getPrototypeOf(t).call(this));babelHelpers.defineProperty(babelHelpers.assertThisInitialized(s),"isReadyToPack",true);babelHelpers.defineProperty(babelHelpers.assertThisInitialized(s),"packStatus",null);babelHelpers.defineProperty(babelHelpers.assertThisInitialized(s),"packPercent",0);babelHelpers.defineProperty(babelHelpers.assertThisInitialized(s),"uploadStatus",null);_classPrivateFieldInitSpec(babelHelpers.assertThisInitialized(s),_currentFileToUpload,{writable:true,value:null});s.setEventNamespace(Options.getEventNamespace());s.item=e;s.id=e.getId();s.name=e.name;s.fileStatus=Options.fileStatus.ready;s.isReadyToPack=e.preparationStatus===s.constructor.preparationStatusIsDone;s.copiesCount=e.getThumbs("getCount")+1;main_core_events.EventEmitter.subscribeOnce(e,"onFileIsDeleted",(function(){s.fileStatus=Options.fileStatus.removed}));if(!s.isReadyToPack){main_core_events.EventEmitter.subscribeOnce(e,"onFileIsPrepared",(function(){s.isReadyToPack=true;s.emit("onReady")}));main_core_events.EventEmitter.emit(e,"onFileHasToBePrepared",new main_core_events.BaseEvent({compatData:[e.getId(),e]}))}return s}babelHelpers.createClass(t,[{key:"isReady",value:function e(){return this.isReadyToPack}},{key:"isRemoved",value:function e(){return this.fileStatus===Options.fileStatus.removed}},{key:"isPacked",value:function e(){return this.packStatus===Options.uploadStatus.done}},{key:"getId",value:function e(){return this.id}},{key:"markAsPacked",value:function e(t){if(t===true){this.packStatus=Options.uploadStatus.done;this.packPercent=100}else{this.packPercent+=t/this.copiesCount;this.packPercent=this.packPercent>100?100:this.packPercent}}},{key:"packFile",value:function e(){var t={error:false,done:true,data:null};if(this.isRemoved()){t.data={removed:"Y",name:this.name};this.markAsPacked(true)}if(this.isPacked()){return t}var i;var s="default";if(this.packStatus===null){t.data=this.item.getProps()||{name:this.name};if(this.item["restored"]){t.data["restored"]=this.item["restored"];delete this.item["restored"]}this.packStatus=Options.uploadStatus.inProgress;i=this.item["file"]}else if(babelHelpers.classPrivateFieldGet(this,_currentFileToUpload)instanceof Blob){i=babelHelpers.classPrivateFieldGet(this,_currentFileToUpload);babelHelpers.classPrivateFieldSet(this,_currentFileToUpload,null)}else{i=this.item.getThumbs(null);if(i===null){this.markAsPacked(true);return t}s=i["thumb"]}var a=100;if(i instanceof Blob){var r=BX.UploaderUtils.getFilePart(i,Options.getUploadLimits("phpUploadMaxFilesize"));if(r&&r!==i){if(r.packages-r.package>1){babelHelpers.classPrivateFieldSet(this,_currentFileToUpload,i)}a=r.size/i.size*100;s=[s,".ch",r.package,".",(r.start>0?r.start:"0")+".chs"+r.packages].join("");r.name=s}i=r}if(i){t.data=t.data||{name:this.name};if(i instanceof Blob){t.data[s]=i}else{t.data["files"]=t.data["files"]||{};t.data["files"][s]=i}}if(t.data){t.done=false;this.markAsPacked(a)}else{this.markAsPacked(true)}return t}},{key:"parseResponse",value:function e(t){var i=t.file,s=t.hash,a=t.status}},{key:"size",get:function e(){return this.item?this.item.size||0:0}}]);return t}(main_core_events.EventEmitter);babelHelpers.defineProperty(PackageFile,"preparationStatusIsDone",4);var getFormDataSize=function e(t){var i=t.entries();var s,a=0,r=0;while((s=i.next())&&s.done===false){var n=babelHelpers.slicedToArray(s.value,2),o=n[0],l=n[1];if(l instanceof Blob){a++;r+=l.size}else{r+=l.toString().length}r+=o.toString().length}return[r,a]};var convertFormDataToObject=function e(t){var i=t.entries();var s;var a={};while((s=i.next())&&s.done===false){var r=babelHelpers.slicedToArray(s.value,2),n=r[0],o=r[1];if(n.indexOf("[")<=0){a[n]=o}else{(function(){var e=[n.substring(0,n.indexOf("["))];n.replace(/\[(.*?)\]/gi,(function(t,i){e.push(i.length>0?i:"")}));var t=void 0;var i=a;while(t=e.shift()){if(t===""){i.push(o);break}else if(e.length<=0){i[t]=o;break}else if(e[0]===""){i[t]=i[t]||[];i=i[t]}else{i[t]=i[t]||{};i=i[t]}}})()}}return a};var copyFormToForm=function e(t,i){var s=t.entries();var a;while((a=s.next())&&a.done===false){var r=babelHelpers.slicedToArray(a.value,2),n=r[0],o=r[1];if(o instanceof Blob){i.append(n,o,o.name)}else{i.append(n,o)}}};var appendToForm=function e(t,i,s){for(var a in i){if(i.hasOwnProperty(a)){var r=(s?s+"[#name#]":"#name#").replace("#name#",a);if(main_core.Type.isPlainObject(i[a])){e(t,i[a],r)}else{if(i[a]instanceof Blob){t.append(r,i[a],i[a]["name"]||a)}else{t.append(r,i[a])}}}}};function _classPrivateFieldInitSpec$1(e,t,i){_checkPrivateRedeclaration$1(e,t);t.set(e,i)}function _checkPrivateRedeclaration$1(e,t){if(t.has(e)){throw new TypeError("Cannot initialize the same private elements twice on an object")}}var _formDataFilesCount=new WeakMap;var _formDataSize=new WeakMap;var Package=function(e){babelHelpers.inherits(t,e);function t(e){var i;var s=e.id,a=e.formData,r=e.files,n=e.uploadFileUrl,o=e.uploadInputName;babelHelpers.classCallCheck(this,t);i=babelHelpers.possibleConstructorReturn(this,babelHelpers.getPrototypeOf(t).call(this));babelHelpers.defineProperty(babelHelpers.assertThisInitialized(i),"length",0);babelHelpers.defineProperty(babelHelpers.assertThisInitialized(i),"filesVirgin",new Set);babelHelpers.defineProperty(babelHelpers.assertThisInitialized(i),"filesInprogress",new Set);babelHelpers.defineProperty(babelHelpers.assertThisInitialized(i),"files",new Map);_classPrivateFieldInitSpec$1(babelHelpers.assertThisInitialized(i),_formDataFilesCount,{writable:true,value:0});_classPrivateFieldInitSpec$1(babelHelpers.assertThisInitialized(i),_formDataSize,{writable:true,value:0});babelHelpers.defineProperty(babelHelpers.assertThisInitialized(i),"makeAPackTimeout",0);babelHelpers.defineProperty(babelHelpers.assertThisInitialized(i),"uploadStatus",Options.uploadStatus.ready);babelHelpers.defineProperty(babelHelpers.assertThisInitialized(i),"errors",[]);babelHelpers.defineProperty(babelHelpers.assertThisInitialized(i),"response",{status:"start"});i.setEventNamespace(Options.getEventNamespace());i.id=s;i.formData=a;i.uploadFileUrl=n;i.uploadInputName=o;i.initFiles(r);console.log("2. Package is created with ",i.filesVirgin.size," files.");i.doneStreaming=i.doneStreaming.bind(babelHelpers.assertThisInitialized(i));i.progressStreaming=i.progressStreaming.bind(babelHelpers.assertThisInitialized(i));return i}babelHelpers.createClass(t,[{key:"getId",value:function e(){return this.id}},{key:"initFiles",value:function e(t){var i=this;t.forEach((function(e){var t=new PackageFile(e);i.filesVirgin.add(t.getId());i.files.set(t.getId(),t)}))}},{key:"prepare",value:function e(){var t=getFormDataSize(this.formData),i=babelHelpers.slicedToArray(t,2),s=i[0],a=i[1];console.log("2.1 Prepare form with files: ",a," and formSize: ",parseInt(s),"B");if(Options.getUploadLimits("phpMaxFileUploads")<=a){this.error("Too many files in your form. ");return false}if(Options.getUploadLimits("phpPostMaxSize")-s<Options.getUploadLimits("phpPostMinSize")){this.error("Too much data in your form. ");return false}var r=0;this.files.forEach((function(e){r+=e.size}));if(Options.getMaxSize()!==null&&Options.getMaxSize()<r){this.error("There is not enough space on your server.");return false}Options.decrementMaxSize(r);babelHelpers.classPrivateFieldSet(this,_formDataSize,s);babelHelpers.classPrivateFieldSet(this,_formDataFilesCount,a);return true}},{key:"run",value:function e(t){if(this.uploadStatus!==Options.uploadStatus.ready){return}console.log("4. Package is running with a stream: ",t);this.uploadStatus=Options.uploadStatus.preparing;return this.startStreaming(t)}},{key:"bindStream",value:function e(t){if(t===this.stream){return}this.stream=t;t.subscribe("done",this.doneStreaming);t.subscribe("progress",this.progressStreaming)}},{key:"unbindStream",value:function e(t){if(t||this.stream){(t||this.stream).unsubscribe("done",this.doneStreaming);(t||this.stream).unsubscribe("progress",this.progressStreaming);if(t===this.stream){delete this.stream}}}},{key:"makeAPack",value:function e(t,i,s){var a=this;while(t-Options.getUploadLimits("phpUploadMaxFilesize")>0&&i>0){if(this.filesVirgin.size<=0){break}var r=this.filesVirgin.entries().next();if(r.done===true){break}var n=babelHelpers.slicedToArray(r.value,1),o=n[0];var l=this.files.get(o);if(!l.isReady()){return l.subscribeOnce("onReady",(function(){a.makeAPack(t,i,s)}))}var d=l.packFile();if(d.data){var u="".concat(this.uploadInputName,"[").concat(l.getId(),"]");var p=new FormData;appendToForm(p,d.data,u);var c=getFormDataSize(p),h=babelHelpers.slicedToArray(c,2),f=h[0],m=h[1];copyFormToForm(p,s);t-=f;i-=m;this.filesInprogress.add(o)}if(d.done===true){this.filesVirgin.delete(o)}}return this.emit("onPackIsReady",s)}},{key:"startStreaming",value:function e(t){this.bindStream(t);this.doStreaming(t)}},{key:"doStreaming",value:function e(t){var i=this;this.subscribeOnce("onPackIsReady",(function(e){var s=e.data;console.log("onPackIsReady: ",s);console.groupEnd("Make a pack.");clearTimeout(i.makeAPackTimeout);i.makeAPackTimeout=0;if(s instanceof FormData){var a=s.entries().next();if(a.done===true&&!a.value){return i.checkAndDone(t)}copyFormToForm(i.formData,s);console.log("4.1. Start streaming");return t.send(i.uploadFileUrl,s)}i.error("Package: error in packing")}));var s=Math.min(Options.getUploadLimits("currentPostSize"),Options.getUploadLimits("phpPostMaxSize")-babelHelpers.classPrivateFieldGet(this,_formDataSize));var a=Options.getUploadLimits("phpMaxFileUploads")-babelHelpers.classPrivateFieldGet(this,_formDataFilesCount);var r=new FormData;console.group("Make a pack.");this.makeAPack(s,a,r);this.makeAPackTimeout=setTimeout((function(){i.emit("onPackIsReady",null)}),Options.getUploadLimits("estimatedTimeForUploadFile")*1e3)}},{key:"doneStreaming",value:function e(t){var i=t.target,s=t.data,a=s.status,r=s.data,n=s.errors;console.log("4.2. Done streaming");if(a==="success"){this.parseResponse(r);if(this.errors.length<=0){this.doStreaming(i)}}else{this.error(n.join(". "))}}},{key:"progressStreaming",value:function e(t){var i=this;var s=t.data;this.filesInprogress.forEach((function(e){var t=i.files.get(e);var a=s*(t.packPercent||0);if(!t["previousPackPercent"]){t["previousPackPercent"]=a}i.emit("fileIsInProgress",{itemId:e,item:t.item,percent:Math.ceil(Math.max(t["previousPackPercent"],a)/100)});t["previousPackPercent"]=a}))}},{key:"parseResponse",value:function e(t){var i=this;var s=function e(t,i){for(var s in i){if(i.hasOwnProperty(s)){t[s]=main_core.Type.isPlainObject(i[s])&&main_core.Type.isPlainObject(t[s])?e(t[s],i[s]):i[s]}}return t};this.response=s(this.response,t);if(t.status==="error"){this.error("Error in a uploading")}else if(!t["files"]){this.error("Unexpected server response.")}else{this.filesInprogress.forEach((function(e){var s=t["files"][e]||{status:"error",errors:["File data is not found"]};if(s.status==="error"||s.status==="uploaded"){i.filesVirgin.delete(e);i.emit(s.status==="error"?"fileIsErrored":"fileIsUploaded",{itemId:e,item:i.files.get(e).item,response:s})}i.files.get(e).parseResponse(s)}));this.filesInprogress.clear()}}},{key:"checkAndDone",value:function e(t){console.log("5. Form has been sent.");if(this.response["status"]==="done"){this.done(t)}else if(this.response["status"]==="start"){this.error("Error with starting package.")}else if(this.response["status"]!=="continue"){this.error("Unknown response")}}},{key:"done",value:function e(t){console.log("5.1 Release the stream");this.unbindStream(t);this.emit("done",{status:this.errors.length<=0?"success":"failed"})}},{key:"error",value:function e(t){var i=this;var s=function e(s){i.emit("fileIsErrored",{itemId:s,item:i.files.get(s).item,response:{error:t,status:"failed"},serverResponse:Object.assign({},i.response)})};this.filesVirgin.forEach(s);this.filesVirgin.clear();this.filesInprogress.forEach(s);this.filesInprogress.clear();this.errors.push(t);console.log("5. Form has been sent with errors: ",this.errors);this.done(this.stream)}},{key:"getServerResponse",value:function e(){return this.response}},{key:"filesCount",get:function e(){return this.filesVirgin.size+this.filesInprogress.size}},{key:"data",get:function e(){return convertFormDataToObject(this.formData)}}]);return t}(main_core_events.EventEmitter);function _classStaticPrivateMethodGet(e,t,i){_classCheckPrivateStaticAccess$1(e,t);return i}function _classStaticPrivateFieldSpecGet$1(e,t,i){_classCheckPrivateStaticAccess$1(e,t);_classCheckPrivateStaticFieldDescriptor$1(i,"get");return _classApplyDescriptorGet$1(e,i)}function _classCheckPrivateStaticFieldDescriptor$1(e,t){if(e===undefined){throw new TypeError("attempted to "+t+" private static field before its declaration")}}function _classCheckPrivateStaticAccess$1(e,t){if(e!==t){throw new TypeError("Private static access of wrong provenance")}}function _classApplyDescriptorGet$1(e,t){if(t.get){return t.get.call(e)}return t.value}var Streams=function(e){babelHelpers.inherits(t,e);function t(){babelHelpers.classCallCheck(this,t);return babelHelpers.possibleConstructorReturn(this,babelHelpers.getPrototypeOf(t).apply(this,arguments))}babelHelpers.createClass(t,null,[{key:"addPackage",value:function e(i){console.log("3. Add to a stream queue.");if(this.maxInstances>0&&_classStaticPrivateFieldSpecGet$1(this,t,_instance).size>this.maxInstances){_classStaticPrivateFieldSpecGet$1(this,t,_packages).set(i)}else{_classStaticPrivateFieldSpecGet$1(this,t,_packages).delete(i);_classStaticPrivateMethodGet(this,t,_runPackage).call(this,i)}if(!window[_classStaticPrivateFieldSpecGet$1(this,t,_hiddenTag)]){window[_classStaticPrivateFieldSpecGet$1(this,t,_hiddenTag)]=_classStaticPrivateMethodGet(this,t,_catchWindow).bind(this);main_core.Event.bind(window,"beforeunload",window[_classStaticPrivateFieldSpecGet$1(this,t,_hiddenTag)])}}}]);return t}(main_core_events.EventEmitter);function _catchWindow(e){if(_classStaticPrivateFieldSpecGet$1(this,Streams,_packages).size>0||_classStaticPrivateFieldSpecGet$1(this,Streams,_instance).size>0){var t=main_core.Loc.getMessage("UPLOADER_UPLOADING_ONBEFOREUNLOAD");(e||window.event).returnValue=t;return t}}function _runPackage(e){var t=this;var i=new Stream;_classStaticPrivateFieldSpecGet$1(this,Streams,_instance).set(i);console.log("3.1. Run package in a stream.");e.subscribeOnce("done",(function(){console.log("6. Package is done so release the stream.");_classStaticPrivateFieldSpecGet$1(t,Streams,_instance).delete(i);i.destroy();if(_classStaticPrivateFieldSpecGet$1(t,Streams,_packages).size>0){var e=babelHelpers.slicedToArray(_classStaticPrivateFieldSpecGet$1(t,Streams,_packages).entries().next().value,1),s=e[0];t.addPackage(s)}else if(_classStaticPrivateFieldSpecGet$1(t,Streams,_instance).size<=0){main_core.Event.unbind(window,"beforeunload",window[_classStaticPrivateFieldSpecGet$1(t,Streams,_hiddenTag)]);delete window[_classStaticPrivateFieldSpecGet$1(t,Streams,_hiddenTag)]}}));e.run(i)}babelHelpers.defineProperty(Streams,"maxInstances",3);var _instance={writable:true,value:new Map};var _packages={writable:true,value:new Map};var _hiddenTag={writable:true,value:Symbol("streams descriptor")};(function(e){e.BX=e["BX"]||{};if(e.BX["UploaderQueue"])return false;var t=e.BX,i={new:0,ready:1,preparing:2,inprogress:3,done:4,failed:5,stopped:6,changed:7,uploaded:8};t.UploaderQueue=function(e,i,s){this.dialogName="BX.UploaderQueue";i=!!i?i:{};this.limits={phpPostMaxSize:i["phpPostMaxSize"],phpUploadMaxFilesize:i["phpUploadMaxFilesize"],uploadMaxFilesize:i["uploadMaxFilesize"]>0?i["uploadMaxFilesize"]:0,uploadFileWidth:i["uploadFileWidth"]>0?i["uploadFileWidth"]:0,uploadFileHeight:i["uploadFileHeight"]>0?i["uploadFileHeight"]:0};this.placeHolder=t(e["placeHolder"]);this.showImage=e["showImage"]!==false&&e["showImage"]!=="N";this.sortItems=e["sortItems"]!==false&&e["sortItems"]!=="N";this.fileCopies=e["copies"];this.fileFields=e["fields"];this.uploader=s;this.itForUpload=new t.UploaderUtils.Hash;this.items=new t.UploaderUtils.Hash;this.itUploaded=new t.UploaderUtils.Hash;this.itFailed=new t.UploaderUtils.Hash;this.thumb={tagName:"LI",className:"bx-bxu-thumb-thumb"};if(!!e["thumb"]){for(var a in e["thumb"]){if(e["thumb"].hasOwnProperty(a)&&this.thumb.hasOwnProperty(a)){this.thumb[a]=e["thumb"][a]}}}t.addCustomEvent(s,"onItemIsAdded",t.delegate(this.addItem,this));t.addCustomEvent(s,"onFileIsDeleted",t.delegate(this.deleteItem,this));t.addCustomEvent(s,"onFileIsReinited",t.delegate(this.reinitItem,this));this.log("Initialized");return this};t.UploaderQueue.prototype={showError:function e(t){this.log("Error! "+t)},log:function e(i){t.UploaderUtils.log("queue",i)},addItem:function s(a,r){var n;if(!this.showImage)n=false;else if(t.type.isDomNode(a))n=t.UploaderUtils.isImage(a.value,null,null);else n=t.UploaderUtils.isImage(a["name"],a["type"],a["size"]);t.onCustomEvent(this.uploader,"onFileIsBeforeCreated",[a,r,n,this.uploader]);var o={copies:this.fileCopies,fields:this.fileFields},l=n?new t.UploaderImage(a,o,this.limits,this.uploader):new t.UploaderFile(a,o,this.limits,this.uploader),d,u,p={status:i.ready};t.onCustomEvent(l,"onFileIsAfterCreated",[l,r,p,this.uploader]);t.onCustomEvent(this.uploader,"onFileIsAfterCreated",[l,r,p,this.uploader]);this.items.setItem(l.id,l);if(r||p["status"]!==i.ready){this.itUploaded.setItem(l.id,l)}else{this.itForUpload.setItem(l.id,l)}if(!!this.placeHolder){if(t(r)){l.thumbNode=u=t(r);u.setAttribute("bx-bxu-item-id",l.id)}else{d=l.makeThumb();u=t.create(this.thumb.tagName,{attrs:{id:l.id+"Item","bx-bxu-item-id":l.id,className:this.thumb.className}});if(t.type.isNotEmptyString(d)){if(this.thumb.tagName=="TR"){d=d.replace(/[\n\t]/gi,"").replace(/^(\s+)(.*?)/gi,"$2").replace(/(.*?)(\s+)$/gi,"$1");if(!!d["trim"])d=d.trim();var c=function e(t,i,s){var a=u.insertCell(-1),r={colspan:true,headers:true,accesskey:true,class:true,contenteditable:true,contextmenu:true,dir:true,hidden:true,id:true,lang:true,spellcheck:true,style:true,tabindex:true,title:true,translate:true},n;a.innerHTML=s;i=i.split(" ");while((n=i.pop())&&n){n=n.split("=");if(n.length==2){n[0]=n[0].replace(/^(\s+)(.*?)/gi,"$2").replace(/(.*?)(\s+)$/gi,"$1").replace(/^["'](.*?)["']$/gi,"$1");n[1]=n[1].replace(/^(\s+)(.*?)/gi,"$2").replace(/(.*?)(\s+)$/gi,"$1").replace(/^["'](.*?)["']$/gi,"$1");if(r[n[0]]===true)a.setAttribute(n[0],n[1]);else a[n[0]]=n[1]}}return""},h=/^<td(.*?)>(.*?)<\/td>/i;e.data1=d;while(h.test(d)){d=d.replace(h,c)}}else{u.innerHTML=d}}else if(t.type.isDomNode(d)){t.adjust(u,{children:[d]})}}if(!!e["jsDD"]&&this.sortItems){if(!this._onbxdragstart){this._onbxdragstart=t.delegate(this.onbxdragstart,this);this._onbxdragstop=t.delegate(this.onbxdragstop,this);this._onbxdrag=t.delegate(this.onbxdrag,this);this._onbxdraghout=t.delegate(this.onbxdraghout,this);this._onbxdestdraghover=t.delegate(this.onbxdestdraghover,this);this._onbxdestdraghout=t.delegate(this.onbxdestdraghout,this);this._onbxdestdragfinish=t.delegate(this.onbxdestdragfinish,this)}t.addClass(u,"bx-drag-draggable");u.onbxdragstart=this._onbxdragstart;u.onbxdragstop=this._onbxdragstop;u.onbxdrag=this._onbxdrag;u.onbxdraghout=this._onbxdraghout;e.jsDD.registerObject(u);u.onbxdestdraghover=this._onbxdestdraghover;u.onbxdestdraghout=this._onbxdestdraghout;u.onbxdestdragfinish=this._onbxdestdragfinish;e.jsDD.registerDest(u);var f=t.findChild(u,{tagName:"INPUT",props:{type:"text"}},true,true);for(var m=0;m<=f.length;m++){t.bind(f[m],"mousedown",t.eventCancelBubble)}}u.setAttribute("bx-item-id",l.id);if(t(r)){t.onCustomEvent(this.uploader,"onFileIsBound",[l.id,l,this.caller,r]);t.onCustomEvent(l,"onFileIsBound",[l.id,l,this.caller,r])}else if(!!r){this.placeHolder.appendChild(u);t.onCustomEvent(this.uploader,"onFileIsAttached",[l.id,l,this.caller,r]);t.onCustomEvent(l,"onFileIsAttached",[l.id,l,this.caller,r])}else{this.placeHolder.appendChild(u);t.onCustomEvent(this.uploader,"onFileIsAppended",[l.id,l,this.caller]);t.onCustomEvent(l,"onFileIsAppended",[l.id,l,this.caller])}}t.onCustomEvent(this.uploader,"onQueueIsChanged",[this,"add",l.id,l])},getItem:function e(i){var s=this.items.getItem(i);if(s)return{item:s,node:s.thumbNode||t(i+"Item")};return null},onbxdragstart:function e(){var i=t.proxy_context,s=i&&i.getAttribute("bx-item-id");if(s){var a=i.innerHTML.replace(new RegExp(s,"gi"),"DragCopy");i.__dragCopyDiv=t.create("DIV",{attrs:{className:"bx-drag-object "+i.className},style:{position:"absolute",zIndex:10,width:i.clientWidth+"px"},html:a});i.__dragCopyPos=t.pos(i);t.onCustomEvent(this.uploader,"onBxDragStart",[i,i.__dragCopyDiv]);document.body.appendChild(i.__dragCopyDiv);t.addClass(i,"bx-drag-source");var r=t("DragCopyProperCanvas"),n,o=this.items.getItem(s);if(r&&o&&t(o.canvas)){n=o.canvas.cloneNode(true);r.parentNode.replaceChild(n,r);n.getContext("2d").drawImage(o.canvas,0,0)}}return true},onbxdragstop:function e(){var i=t.proxy_context;if(i.__dragCopyDiv){t.removeClass(i,"bx-drag-source");i.__dragCopyDiv.parentNode.removeChild(i.__dragCopyDiv);i.__dragCopyDiv=null;delete i["__dragCopyDiv"];delete i["__dragCopyPos"]}return true},onbxdrag:function e(i,s){var a=t.proxy_context,r=a.__dragCopyDiv;if(r){if(a.__dragCopyPos){if(!a.__dragCopyPos.deltaX)a.__dragCopyPos.deltaX=a.__dragCopyPos.left-i;if(!a.__dragCopyPos.deltaY)a.__dragCopyPos.deltaY=a.__dragCopyPos.top-s;i+=a.__dragCopyPos.deltaX;s+=a.__dragCopyPos.deltaY}r.style.left=i+"px";r.style.top=s+"px"}},onbxdraghout:function e(t,i,s){},onbxdestdraghover:function e(i){if(!i||!i.hasAttribute("bx-bxu-item-id")||!this.items.hasItem(i.getAttribute("bx-bxu-item-id")))return;var s=t.proxy_context;t.addClass(s,"bx-drag-over");return true},onbxdestdraghout:function e(){var i=t.proxy_context;t.removeClass(i,"bx-drag-over");return true},onbxdestdragfinish:function e(i){var s=t.proxy_context;t.removeClass(s,"bx-drag-over");if(s==i||!t.hasClass(i,"bx-drag-draggable"))return true;var a=i.getAttribute("bx-bxu-item-id");if(!this.items.hasItem(a))return;var r=s.parentNode,n=r.childNodes.length,o,l,d,u;for(u=0;u<n;u++){if(r.childNodes[u]==s)s.number=u;else if(r.childNodes[u]==i)i.number=u;if(i.number>0&&s.number>0)break}if(this.itForUpload.hasItem(a)){o=s.number<=i.number?"beforeItem":s.nextSibling?"afterItem":"inTheEnd";l=null;if(o!="inTheEnd"){for(u=s.number+(o=="beforeItem"?0:1);u<n;u++){if(this.itForUpload.hasItem(r.childNodes[u].getAttribute("bx-bxu-item-id"))){l=r.childNodes[u].getAttribute("bx-bxu-item-id");break}}if(l===null)o="inTheEnd"}d=this.itForUpload.removeItem(i.getAttribute("bx-bxu-item-id"));if(o!="inTheEnd")this.itForUpload.insertBeforeItem(d.id,d,l);else this.itForUpload.setItem(d.id,d)}o=s.number<=i.number?"beforeItem":s.nextSibling?"afterItem":"inTheEnd";l=null;if(o!="inTheEnd"){for(u=s.number+(o=="beforeItem"?0:1);u<n;u++){if(this.items.hasItem(r.childNodes[u].getAttribute("bx-bxu-item-id"))){l=r.childNodes[u].getAttribute("bx-bxu-item-id");break}}if(l===null)o="inTheEnd"}d=this.items.removeItem(i.getAttribute("bx-bxu-item-id"));if(o!="inTheEnd")this.items.insertBeforeItem(d.id,d,l);else this.items.setItem(d.id,d);i.parentNode.removeChild(i);if(s.number<=i.number){s.parentNode.insertBefore(i,s)}else if(s.nextSibling){s.parentNode.insertBefore(i,s.nextSibling)}else{for(u=0;u<n;u++){if(r.childNodes[u]==s)s.number=u;else if(r.childNodes[u]==i)i.number=u}if(s.number<=i.number){s.parentNode.insertBefore(i,s)}else{s.parentNode.appendChild(i)}}t.onCustomEvent(s,"onFileOrderIsChanged",[s.id,s,this.caller]);t.onCustomEvent(this.uploader,"onQueueIsChanged",[this,"sort",s.id,s]);return true},deleteItem:function i(s,a){var r=this.getItem(s),n;if(r&&(!this.placeHolder||(n=r.node)&&n)){if(!!n){if(!!e["jsDD"]){n.onmousedown=null;n.onbxdragstart=null;n.onbxdragstop=null;n.onbxdrag=null;n.onbxdraghout=null;n.onbxdestdraghover=null;n.onbxdestdraghout=null;n.onbxdestdragfinish=null;n.__bxpos=null;e.jsDD.arObjects[n.__bxddid]=null;delete e.jsDD.arObjects[n.__bxddid];e.jsDD.arDestinations[n.__bxddeid]=null;delete e.jsDD.arDestinations[n.__bxddeid]}t.unbindAll(n);if(a["replaced"]!==true)n.parentNode.removeChild(n)}this.items.removeItem(s);this.itUploaded.removeItem(s);this.itFailed.removeItem(s);this.itForUpload.removeItem(s);t.onCustomEvent(this.uploader,"onQueueIsChanged",[this,"delete",s,a]);return true}return false},reinitItem:function i(s,a){var r,n;if(!!this.placeHolder&&this.items.hasItem(s)&&(r=t(s+"Item"))&&r){n=a.makeThumb();if(t.type.isNotEmptyString(n)){if(this.thumb.tagName=="TR"){n=n.replace(/[\n\t]/gi,"").replace(/^(\s+)(.*?)/gi,"$2").replace(/(.*?)(\s+)$/gi,"$1");if(!!n["trim"])n=n.trim();var o=function e(t,i,s){var a=r.insertCell(-1),n={colspan:true,headers:true,accesskey:true,class:true,contenteditable:true,contextmenu:true,dir:true,hidden:true,id:true,lang:true,spellcheck:true,style:true,tabindex:true,title:true,translate:true},o;a.innerHTML=s;i=i.split(" ");while((o=i.pop())&&o){o=o.split("=");if(o.length==2){o[0]=o[0].replace(/^(\s+)(.*?)/gi,"$2").replace(/(.*?)(\s+)$/gi,"$1").replace(/^["'](.*?)["']$/gi,"$1");o[1]=o[1].replace(/^(\s+)(.*?)/gi,"$2").replace(/(.*?)(\s+)$/gi,"$1").replace(/^["'](.*?)["']$/gi,"$1");if(n[o[0]]===true)a.setAttribute(o[0],o[1]);else a[o[0]]=o[1]}}return""},l=/^<td(.*?)>(.*?)<\/td>/i;e.data1=n;while(l.test(n)){n=n.replace(l,o)}}else{r.innerHTML=n}}else if(t.type.isDomNode(n)){while(t(r.firstChild)){t.remove(r.firstChild)}t.adjust(r,{children:[n]})}t.onCustomEvent(this.uploader,"onFileIsAppended",[a.id,a,this.caller]);t.onCustomEvent(a,"onFileIsAppended",[a.id,a,this.caller])}},clear:function e(){var t;while((t=this.items.getFirst())&&!!t){this.deleteItem(t.id,t)}},restoreFiles:function e(i,s,a){i.reset();var r,n,o;while((r=i.getNext())&&r){o=this.itFailed.hasItem(r.id);if(s===true){this.itFailed.removeItem(r.id)}if(!this.items.hasItem(r.id)||this.itFailed.hasItem(r.id)){continue}if(a===true||a!==false&&o){delete r["uploadStatus"];delete r.file["uploadStatus"];delete r.file["firstChunk"];delete r.file["package"];delete r.file["packages"];if(r.file["copies"]){r.file["copies"].reset();while((n=r.file["copies"].getNext())&&n){delete n["uploadStatus"];delete n["firstChunk"];delete n["package"];delete n["packages"]}r.file["copies"].reset()}r["restored"]=a===true?"Y":"C"}else{if(o){if(r.file["package"]){r.file["package"]--}if(r.file["copies"]){r.file["copies"].reset();while((n=r.file["copies"].getNext())&&n){delete n["uploadStatus"];delete n["firstChunk"];delete n["package"];delete n["packages"]}r.file["copies"].reset()}}r["restored"]="C"}this.itUploaded.removeItem(r.id);this.itForUpload.setItem(r.id,r);t.onCustomEvent(r,"onUploadRestore",[r])}}};return i})(window);(function(window){window.BX=window["BX"]||{};if(window.BX["UploaderUtils"])return false;var BX=window.BX;BX.UploaderLog=[];BX.UploaderDebug=false;var statuses={new:0,ready:1,preparing:2,inprogress:3,done:4,failed:5,stopped:6,changed:7,uploaded:8};BX.UploaderUtils={statuses:statuses,getId:function e(){return(new Date).valueOf()+Math.round(Math.random()*1e6)},log:function e(){if(BX.UploaderDebug===true){console.log(arguments)}else{BX.UploaderLog.push(arguments)}},Hash:function(){var e=function e(){this.length=0;this.items={};this.order=[];var t;if(arguments.length==1&&BX.type.isArray(arguments[0])&&arguments[0].length>0){var i=arguments[0];for(t=0;t<i.length;t++){if(i[t]&&babelHelpers.typeof(i[t])=="object"&&i[t]["id"]){this.setItem(i[t]["id"],i[t])}}}else{for(t=0;t<arguments.length;t+=2){this.setItem(arguments[t],arguments[t+1])}}};e.prototype={getIds:function e(){return this.order},getQueue:function e(t){t+="";return BX.util.array_search(t,this.order)},getByOrder:function e(t){return this.getItem(this.order[t])},removeItem:function e(t){t+="";var i,s;if(typeof this.items[t]!="undefined"){i=this.items[t];s=this.getQueue(t);this.pointer-=this.pointer>=s?1:0;delete this.items[t];this.order=BX.util.deleteFromArray(this.order,s);this.length=this.order.length}return i},getItem:function e(t){t+="";return this.items[t]},unshiftItem:function e(t,i){t+="";if(typeof i!="undefined"){if(typeof this.items[t]=="undefined"){this.order.unshift(t);this.length=this.order.length}this.items[t]=i}return i},setItem:function e(t,i){t+="";if(typeof i!="undefined"){if(typeof this.items[t]=="undefined"){this.order.push(t);this.length=this.order.length}this.items[t]=i}return i},hasItem:function e(t){t+="";return typeof this.items[t]!="undefined"},insertBeforeItem:function e(t,i,s){t+="";if(typeof i!="undefined"){if(typeof this.items[t]=="undefined"){this.order.splice(this.getQueue(s),0,t);this.length=this.order.length}this.items[t]=i}return i},getFirst:function e(){var t,i=null;for(var s=0;s<this.order.length;s++){t=this.order[s];if(!!t&&this.hasItem(t)){i=this.getItem(t);break}}return i},getNext:function e(){this.pointer=0<=this.pointer&&this.pointer<this.order.length?this.pointer:-1;var t=this.getItem(this.order[this.pointer+1]);if(!!t)this.pointer++;else this.pointer=-1;return t},getPrev:function e(){this.pointer=0<=this.pointer&&this.pointer<this.order.length?this.pointer:0;var t=this.getItem(this.order[this.pointer-1]);if(!!t)this.pointer--;return t},reset:function e(){this.pointer=-1},setPointer:function e(t){this.pointer=this.getQueue(t);return this.pointer},getLast:function e(){var t,i=null;for(var s=this.order.length;s>=0;s--){t=this.order[s];if(!!t&&this.hasItem(t)){i=this.getItem(t);break}}return i}};return e}(),getFileNameOnly:function e(t){var i="\\",s=t.lastIndexOf(i),a=t.length;if(s==-1){i="/";s=t.lastIndexOf(i)}if(s+1==t.length){a=s;s=t.substring(0,a).lastIndexOf(i)}t=t.substring(s+1,a);if(i=="/"&&t.indexOf("?")>0){t=t.substring(0,t.indexOf("?"))}if(t=="")t="noname";return t},isImageExt:function e(t){return BX.message("bxImageExtensions")&&BX.type.isNotEmptyString(t)?new RegExp("(?:^|\\W)("+t+")(?:\\W|$)","gi").test(BX.message("bxImageExtensions")):false},isImage:function e(t,i,s){s=BX.type.isNumber(s)?s:BX.type.isNotEmptyString(s)&&!/[\D]+/gi.test(s)?parseInt(s):null;return(i===null||(i||"").indexOf("image/")===0)&&(s===null||s<20*1024*1024)&&BX.UploaderUtils.isImageExt((t||"").lastIndexOf(".")>0?t.substr(t.lastIndexOf(".")+1).toLowerCase():"")},scaleImage:function e(t,i,s){var a=parseInt(t["width"]),r=parseInt(t["height"]);s=!s&&!!i["type"]?i["type"]:s;i=!!i?i:{};i.width=parseInt(!!i.width?i.width:0);i.height=parseInt(!!i.height?i.height:0);var n={bNeedCreatePicture:false,source:{x:0,y:0,width:0,height:0},destin:{x:0,y:0,width:0,height:0}},o,l;if(!(a>0||r>0)){BX.DoNothing()}else{if(!BX.type.isNotEmptyString(s)){s="inscribed"}var d,u;if(s.indexOf("proportional")>=0){o=Math.max(a,r);l=Math.min(a,r)}else{o=a;l=r}if(s=="exact"){var p=a/r<i["width"]/i["height"]?i["width"]/a:i["height"]/r,c=Math.max(0,Math.round(a/2-i["width"]/2/p)),h=Math.max(0,Math.round(r/2-i["height"]/2/p));n.bNeedCreatePicture=true;n.coeff=p;n.destin["width"]=i["width"];n.destin["height"]=i["height"];n.source["x"]=c;n.source["y"]=h;n.source["width"]=Math.round(i["width"]/p,0);n.source["height"]=Math.round(i["height"]/p,0)}else{if(s=="circumscribed"){d={width:o>0?i["width"]/o:1,height:l>0?i["height"]/l:1};u=Math.max(d["width"],d["height"],1)}else{d={width:o>0?i["width"]/o:1,height:l>0?i["height"]/l:1};u=Math.min(d["width"],d["height"],1);u=0<u?u:1}n.bNeedCreatePicture=u!=1;n.coeff=u;n.destin["width"]=Math.max(1,parseInt(u*a));n.destin["height"]=Math.max(1,parseInt(u*r));n.source["x"]=0;n.source["y"]=0;n.source["width"]=a;n.source["height"]=r}}return n},dataURLToBlob:function e(t){var i=";base64,",s,a,r,n;if(t.indexOf(i)==-1){s=t.split(",");a=s[0].split(":")[1];r=s[1];return new Blob([r],{type:a})}s=t.split(i);a=s[0].split(":")[1];r=window.atob(s[1]);n=r.length;var o=new Uint8Array(n);for(var l=0;l<n;++l){o[l]=r.charCodeAt(l)}return new Blob([o],{type:a})},sizeof:function e(t){var i=0,s;for(s in t){if(t.hasOwnProperty(s)){i+=s.length;if(babelHelpers.typeof(t[s])=="object"){if(t[s]===null)BX.DoNothing();else if(t[s]["size"]>0)i+=t[s].size;else i+=BX.UploaderUtils.sizeof(t[s])}else if(typeof t[s]=="number"){i+=t[s].toString().length}else if(!!t[s]&&t[s].length>0){i+=t[s].length}}}return i},FormToArray:function e(t,i){return BX.ajax.prepareForm(t,i)},getFormattedSize:function e(t,i){var s=["b","Kb","Mb","Gb","Tb"],a=0;while(t>=1024&&a<4){t/=1024;a++}return Math.round(t*(i>0?i*10:1))/(i>0?i*10:1)+" "+BX.message("FILE_SIZE_"+s[a])},bindEvents:function bindEvents(obj,event,func){var funcs=[],ii;if(typeof func=="string"){eval("funcs.push("+func+");")}else if(!!func["length"]&&func["length"]>0){for(ii=0;ii<func.length;ii++){if(typeof func[ii]=="string")eval("funcs.push("+func[ii]+");");else funcs.push(func[ii])}}else funcs.push(func);if(funcs.length>0){for(ii=0;ii<funcs.length;ii++){BX.addCustomEvent(obj,event,funcs[ii])}}},applyFilePart:function e(t,i){if(BX.type.isDomNode(t)){t.uploadStatus=statuses.done}else if(t==i){t.uploadStatus=statuses.done}else if(t.blobed===true){t.uploadStatus=t.package+1>=t.packages?statuses.done:statuses.inprogress;if(t.uploadStatus==statuses.inprogress)t.package++}return true},getFilePart:function e(t,i){var s,a=i,r,n;if(BX.type.isDomNode(t)){s=t}else if(i<=0||t.size<=i){s=t}else if(t["packages"]&&t["packages"]<=t["package"]){s=null}else if(window.Blob||window.MozBlobBuilder||window.WebKitBlobBuilder||window.BlobBuilder){if(t["packages"]){t.package++;r=t.package*a;n=r+a}else{t.packages=Math.ceil(t.size/a);t.package=0;r=0;n=a}if("mozSlice"in t)s=t.mozSlice(r,n,t.type);else if("webkitSlice"in t)s=t.webkitSlice(r,n,t.type);else if("slice"in t)s=t.slice(r,n,t.type);else s=t.Slice(r,n,t.type);for(var o in t){if(t.hasOwnProperty(o)){s[o]=t[o]}}s["name"]=t["name"];s["start"]=r;s["package"]=t.package;s["packages"]=t.packages}return s},makeAnArray:function e(t,i){t=!!t?t:{files:[],props:{}};var s;for(var a in i){if(i.hasOwnProperty(a)){if(babelHelpers.typeof(i[a])=="object"&&i[a].length>0){t[a]=!!t[a]?t[a]:[];for(s=0;s<i[a].length;s++){t[a].push(i[a][s])}}else{for(s in i[a]){if(i[a].hasOwnProperty(s)){t[a]=!!t[a]?t[a]:{};t[a][s]=i[a][s]}}}}}return t},appendToForm:function e(t,i,s){if(!!s&&babelHelpers.typeof(s)=="object"){for(var a in s){if(s.hasOwnProperty(a)){BX.UploaderUtils.appendToForm(t,i+"["+a+"]",s[a])}}}else{t.append(i,!!s?s:"")}},FormData:function e(){return new(BX.Uploader.getInstanceName()=="BX.UploaderSimple"?FormDataLocal:window.FormData)},prepareData:function e(t){var i={};if(null!=t){if(babelHelpers.typeof(t)=="object"){for(var s in t){if(t.hasOwnProperty(s)){var a=BX.util.urlencode(s);if(babelHelpers.typeof(t[s])=="object")i[a]=BX.UploaderUtils.prepareData(t[s]);else i[a]=BX.util.urlencode(t[s])}}}else i=BX.util.urlencode(t)}return i}};var FormDataLocal=function e(){var t;do{t=Math.floor(Math.random()*99999)}while(BX("form-"+t));this.local=true;this.form=BX.create("FORM",{props:{id:"form-"+t,method:"POST",enctype:"multipart/form-data",encoding:"multipart/form-data"},style:{display:"none"}});document.body.appendChild(this.form)};FormDataLocal.prototype={append:function e(t,i){if(BX.type.isDomNode(i)){this.form.appendChild(i)}else{this.form.appendChild(BX.create("INPUT",{props:{type:"hidden",name:t,value:i}}))}}};BX.UploaderUtils.slice=function(e,t,i){var s=null;if("mozSlice"in e)s=e.mozSlice(t,i);else if("webkitSlice"in e)s=e.webkitSlice(t,i);else if("slice"in e)s=e.slice(t,i);else s=e.Slice(t,i,e.type);return s};BX.UploaderUtils.readFile=function(e,t,i){if(window["FileReader"]){var s=new FileReader;s.onload=s.onerror=t;i=i||"readAsDataURL";if(s[i]){s[i](e);return s}}return false}})(window);var UploaderQueue=window.BX["UploaderQueue"];var UploaderUtils=window.BX["UploaderUtils"];var Uploader=function(){function e(t){babelHelpers.classCallCheck(this,e);babelHelpers.defineProperty(this,"fileInput",null);babelHelpers.defineProperty(this,"form",null);babelHelpers.defineProperty(this,"limits",{});babelHelpers.defineProperty(this,"packages",new Map);var i=t.input,s=t.uploadFileUrl,a=t.id,r=t.CID,n=t.controlId,o=t.dropZone,l=t.placeHolder,d=t.events;if(main_core.Type.isStringFilled(s)){this.uploadFileUrl=s}i=main_core.Type.isStringFilled(i)?document.getElementById(i):i;if(main_core.Type.isDomNode(i)){this.fileInput=i;this.form=i.form;this.uploadFileUrl=this.uploadFileUrl||this.form.getAttribute("action")}else if(i!==null){main_core.Runtime.debug(main_core.Loc.getMessage("UPLOADER_INPUT_IS_NOT_DEFINED"));return}if(!this.uploadFileUrl){main_core.Runtime.debug(main_core.Loc.getMessage("UPLOADER_ACTION_URL_NOT_DEFINED"));return}this.constructor.justCounter++;var u=UploaderUtils.getId();this.id=main_core.Type.isStringFilled(a)?a:["bitrixUploaderID",u].join("");this.CID=main_core.Type.isStringFilled(r)?r:"CID"+u;this.controlId=n||"bitrixUploader";this.onChange=this.onChange.bind(this);this.setLimits(t);this.initParams(t);this.init(this.fileInput);this.dropZone=this.initDropZone(o);this.bindUserEvents(d);this.initFilesQueue(t);BX.onCustomEvent(window,"onUploaderIsInited",[this.id,this]);e.repo.set(this.id,this)}babelHelpers.createClass(e,[{key:"setLimits",value:function e(t){var i=t.uploadMaxFilesize,s=t.uploadFileWidth,a=t.uploadFileHeight,r=t.allowUpload,n=t.allowUploadExt;this.limits={uploadMaxFilesize:i||0,uploadFileWidth:s||0,uploadFileHeight:a||0,uploadFileExt:"",uploadFile:this.fileInput?this.fileInput.getAttribute("accept"):"",allowUpload:r,allowUploadExt:n};var o=[];if(main_core.Type.isStringFilled(this.limits["uploadFile"])){o.push(this.limits["uploadFile"])}if(r==="I"){o.push("image/*")}if(main_core.Type.isStringFilled(n)){var l=n.indexOf(",")>=0?",":" ";var d=[];n.split(l).forEach((function(e){d.push(e.trim().replace(".",""));o.push("."+e.trim().replace(".",""))}));if(d){this.limits["uploadFileExt"]=d}}this.limits["uploadFile"]=o.join(", ")}},{key:"initParams",value:function e(t){var i=t.uploadMethod,s=t.uploadFormData,a=t.filesInputMultiple,r=t.uploadInputName,n=t.uploadInputInfoName,o=t.deleteFileOnServer,l=t.pasteFileHashInForm;this.params={filesInputMultiple:this.fileInput&&this.fileInput["multiple"]||a?"multiple":false,uploadFormData:s==="N"?"N":"Y",uploadMethod:i==="immediate"?"immediate":"deferred",uploadInputName:main_core.Type.isStringFilled(r)?r:"bxu_files",uploadInputInfoName:main_core.Type.isStringFilled(n)?n:"bxu_info",deleteFileOnServer:!(o===false||o==="N"),filesInputName:this.fileInput&&this.fileInput["name"]?this.fileInput["name"]:"FILES",pasteFileHashInForm:!(l===false||l==="N")}}},{key:"init",value:function e(t){if(t===null){return true}if(main_core.Type.isDomNode(t)){var i=this.makeFileInput(t);if(t===this.fileInput){this.fileInput=i}if(i){return true}}return false}},{key:"initDropZone",value:function e(t){var i=this;var s=new DropZone(t);main_core_events.EventEmitter.subscribe(s,Options.getEventName("caught"),(function(e){var t=e.data;i.onChange(t)}));main_core_events.EventEmitter.subscribe(this,Options.getEventName("destroy"),(function(){main_core_events.EventEmitter.unsubscribeAll(s,Options.getEventName("caught"));s.destroy()}));return s}},{key:"initFilesQueue",value:function e(t){var i=t.fields,s=t.copies,a=t.placeHolder,r=t.showImage,n=t.sortItems,o=t.thumb,l=t.queueFields;var d={fields:l&&l["fields"]?l["fields"]:i,copies:l&&l["copies"]?l["copies"]:s,placeHolder:l&&l["placeHolder"]?l["placeHolder"]:a,showImage:l&&l["showImage"]?l["showImage"]:r,sortItems:l&&l["sortItems"]?l["sortItems"]:n,thumb:l&&l["thumb"]?l["thumb"]:o};this.queue=new UploaderQueue(d,this.limits,this)}},{key:"bindUserEvents",value:function e(t){if(!main_core.Type.isPlainObject(t)){return}for(var i in t){if(t.hasOwnProperty(i)){main_core_events.EventEmitter.subscribe(this,i,t[i])}}}},{key:"makeFileInput",value:function e(t){if(!main_core.Type.isDomNode(t)){return false}main_core.Event.unbindAll(t,"change");var i=t.cloneNode(true);i.value="";i.setAttribute("name",this.params["uploadInputName"]+"[]");i.setAttribute("multiple",this.params["filesInputMultiple"]);i.setAttribute("accept",this.limits["uploadFile"]);t.parentNode.replaceChild(i,t);BX.onCustomEvent(this,"onFileinputIsReinited",[i,this]);main_core.Event.bind(i,"change",this.onChange);return i}},{key:"onChange",value:function e(t){if(!t){return}if(t["preventDefault"]){t.preventDefault()}if(t["stopPropagation"]){t.stopPropagation()}var i=[];if(main_core.Type.isArray(t)){i=t}else if(main_core.Type.isObject(t)){if(t["target"]){var s=t["target"];i=s.files;if(!s||s.disabled){return false}BX.onCustomEvent(this,"onFileinputIsChanged",[s,this]);this.init(s)}else if(t["files"]){i=t["files"]}}this.onAttach(i);return false}},{key:"onAttach",value:function e(t,i,s){var a=this;if(!t||!t["length"]){return false}s=s!==false;t=babelHelpers.toConsumableArray(t);i=i&&main_core.Type.isArray(i)?babelHelpers.toConsumableArray(i):[];BX.onCustomEvent(this,"onAttachFiles",[t,i,this]);var r=false;babelHelpers.toConsumableArray(t).forEach((function(e,t){var n="";var o=(e["type"]||"").toLowerCase();if(main_core.Type.isDomNode(e)&&e.value){n=(e.value.name||"").split(".").pop()}else{n=(e["name"]||e["tmp_url"]||"").split(".").pop();if(n.indexOf("?")>0){n=n.substr(0,n.indexOf("?"))}}n=n.toLowerCase();if(s){var l=[];if(a.limits["uploadFile"].indexOf("image/")>=0&&o.indexOf("image/")<0&&Options.getImageExtensions().indexOf(n)<0){l.push("File type is not an image like.")}if(a.limits["uploadFileExt"].length>0){if(a.limits["uploadFileExt"].indexOf(n)<0){l.push("File extension ".concat(n," is in ").concat(a.limits["uploadFileExt"]))}else{l.pop()}}if(a.limits["uploadMaxFilesize"]>0&&e.size>a.limits["uploadMaxFilesize"]){l.push("File size ".concat(e.size," is bigger than ").concat(a.limits["uploadMaxFilesize"]))}if(l.length>0){return}}if(String["normalize"]){e.name=String(e.name).normalize()}BX.onCustomEvent(a,"onItemIsAdded",[e,i[t]||null,a]);r=true}));if(r&&this.params["uploadMethod"]==="immediate"){this.submit()}return false}},{key:"getFormData",value:function e(){var t=new FormData(this.params["uploadFormData"]==="Y"&&this.form?this.form:undefined);var i=t.entries();var s;while((s=i.next())&&s.done===false){var a=babelHelpers.slicedToArray(s.value,1),r=a[0];if(r.indexOf(this.params["filesInputName"])===0||r.indexOf(this.params["uploadInputInfoName"])===0||r.indexOf(this.params["uploadInputName"])===0){t.delete(r)}}t.append("AJAX_POST","Y");t.append("USER_ID",main_core.Loc.getMessage("USER_ID"));t.append("sessid",BX.bitrix_sessid());if(BX.message.SITE_ID){t.append("SITE_ID",BX.message.SITE_ID)}t.append(this.params["uploadInputInfoName"]+"[controlId]",this.controlId);t.append(this.params["uploadInputInfoName"]+"[CID]",this.CID);t.append(this.params["uploadInputInfoName"]+"[uploadInputName]",this.params["uploadInputName"]);t.append(this.params["uploadInputInfoName"]+"[version]",Options.getVersion());return t}},{key:"submit",value:function e(){var t=this;if(this.queue.itForUpload.length<=0){BX.onCustomEvent(this,"onStart",[null,{filesCount:0},this]);BX.onCustomEvent(this,"onDone",[null,null,{filesCount:0}]);BX.onCustomEvent(this,"onFinish",[null,null,{filesCount:0}]);return}var i=Object.values(this.queue.itForUpload.items);var s=this.getFormData();var a={};var r={post:{data:a,size:0,filesCount:i.length},filesCount:i.length};var n=new main_core_events.BaseEvent;n.setCompatData([r,this.queue.itForUpload]);n.setData({formData:s,data:a,files:i});main_core_events.EventEmitter.emit(this,"onPackageIsInitialized",n);appendToForm(s,r.post.data);if(r.post.data!==a){appendToForm(s,a)}var o="pIndex"+((new Date).valueOf()+Math.round(Math.random()*1e6));s.append(this.params["uploadInputInfoName"]+"[packageIndex]",o);s.append(this.params["uploadInputInfoName"]+"[mode]","upload");s.append(this.params["uploadInputInfoName"]+"[filesCount]",i.length);if(this.packages.size<=0){console.group("Upload")}console.log("1. Create a new Package");var l=new Package({id:o,formData:s,files:i,uploadFileUrl:this.uploadFileUrl,uploadInputName:this.params["uploadInputName"]});this.queue.itForUpload=new UploaderUtils.Hash;var d=new main_core_events.BaseEvent;d.setCompatData([o,Object.assign({post:{data:l.data,filesCount:i.length}},l),this]);d.setData({package:l});main_core_events.EventEmitter.emit(this,"onStart",d);this.packages.set(l.getId(),l);main_core_events.EventEmitter.emit(this,"onBusy");l.subscribeOnce("done",(function(e){var i=e.target,s=e.data.status;var a=new main_core_events.BaseEvent;a.setCompatData([{},o,l,l.getServerResponse()]);a.setData({package:l,response:l.getServerResponse()});main_core_events.EventEmitter.emit(t,"onDone",a);if(s==="failed"){main_core_events.EventEmitter.emit(t,"onError",new main_core_events.BaseEvent({compatData:[{},o,l.getServerResponse()]}))}t.packages.delete(i.getId());if(t.packages.size<=0){setTimeout((function(){var e=new main_core_events.BaseEvent;e.setCompatData([{},o,l,l.getServerResponse()]);e.setData({package:l,response:l.getServerResponse()});main_core_events.EventEmitter.emit(t,"onFinish",e);console.groupEnd("Upload")}))}}));l.subscribe("fileIsUploaded",(function(e){var i=e.data,s=i.itemId,a=i.item,r=i.response;t.queue.itUploaded.setItem(s,a);BX.onCustomEvent(t,"onFileIsUploaded",[s,a,r]);BX.onCustomEvent(a,"onUploadDone",[a,r,t,l.getId()])}));l.subscribe("fileIsErrored",(function(e){var i=e.data,s=i.itemId,a=i.item,r=i.response;t.queue.itFailed.setItem(s,a);BX.onCustomEvent(t,"onFileIsUploadedWithError",[s,a,r,t,l.getId()]);BX.onCustomEvent(a,"onUploadError",[a,r,t,l.getId()])}));l.subscribe("fileIsInProgress",(function(e){var i=e.data,s=i.item,a=i.percent;BX.onCustomEvent(s,"onUploadProgress",[s,a,t,l.getId()])}));if(l.prepare()){i.forEach((function(e){BX.onCustomEvent(e,"onUploadStart",[e,0,t,l.getId()])}));Streams.addPackage(l)}}},{key:"log",value:function e(t){}},{key:"destruct",value:function e(){main_core_events.EventEmitter.emit(this,Options.getEventName("destroy"));delete this.dropZone}},{key:"getItem",value:function e(t){return this.queue.getItem(t)}},{key:"getItems",value:function e(){return this.queue.items}},{key:"restoreItems",value:function e(){this.queue.restoreFiles.apply(this.queue,arguments)}},{key:"clear",value:function e(){var t;while((t=this.queue.items.getFirst())&&t){t.deleteFile()}}},{key:"controlID",get:function e(){return this.controlId}},{key:"dialogName",get:function e(){return"BX.Uploader"}},{key:"length",get:function e(){return this.queue.itForUpload.length}},{key:"streams",get:function e(){var t=this;if(!this["#_streams"]){this["#_streams"]={packages:{getItem:function e(i){return t.packages.get(i)}}}}return this["#_streams"]}}],[{key:"getById",value:function e(t){return this.repo.get(t)}},{key:"getInstanceById",value:function e(t){return this.repo.get(t)}},{key:"getInstanceName",value:function e(){return"BX.Uploader"}}]);return e}();babelHelpers.defineProperty(Uploader,"repo",new Map);babelHelpers.defineProperty(Uploader,"justCounter",0);babelHelpers.defineProperty(Uploader,"getInstance",(function(e){BX.onCustomEvent(window,"onUploaderIsAlmostInited",["BX.Uploader",e]);return new this(e)}));var Manager=function(){function e(){babelHelpers.classCallCheck(this,e)}babelHelpers.createClass(e,null,[{key:"getById",value:function e(t){return Uploader.getById(t)}}]);return e}();exports.UploaderManager=Manager;exports.Uploader=Uploader})(this.BX=this.BX||{},BX,BX.Event);
//# sourceMappingURL=uploader.map.js